package com.scommunity.admin.controller;

import com.scommunity.common.ResponseResult;
import com.scommunity.domain.Image;
import com.scommunity.service.IImageService;
import com.scommunity.utils.MinioUtils;
import io.minio.GetObjectResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/image")
public class ImageController{

    @Autowired
    private IImageService imageService;
    @Autowired
    private MinioUtils minioUtils;

    @GetMapping("/list")
    public ResponseResult list(){
        List<Image> imageList = imageService.getList();
        return ResponseResult.success(imageList);
    }


    @PostMapping("/add")
    public ResponseResult add(@RequestBody Image image){
        imageService.add(image);
//        imageService.save(image);,
        return ResponseResult.success();
    }

//    @CacheEvict(value = "imageList", allEntries = true)
    @PostMapping("/update")
    public ResponseResult update(@RequestBody Image image){
        imageService.updateById(image);
        return ResponseResult.success();
    }


    @PostMapping("/upload")
    public ResponseResult update(MultipartFile file){
        String imagePath = imageService.upload(file);
        return ResponseResult.success(imagePath);
    }

    @PostMapping("/deleteimage")
    public ResponseResult deleteImage(@RequestBody Map fileImage){
        String image = (String)fileImage.get("fileImage");
        minioUtils.removeObject(image);
//        imageService.updateByImagePath(image);
        return ResponseResult.success();
    }

    /**
     * 轮播图下载
     * @param fileName
     * @param response
     */
    @GetMapping("/loadimage")
    public void loadImage(String fileName, HttpServletResponse response){
        GetObjectResponse object = minioUtils.getObject(fileName);
        String type = object.headers().get("Content-Type");
        response.setContentType(type);
        try {
            IOUtils.copy(object,response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
//        return ResponseResult.success();
    }
}
